package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.to.SkuInfoEntity;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeignService productFeignService;



    @Override

    public PageUtils queryPage(Map<String, Object> params) {

        LambdaQueryWrapper<WareSkuEntity> wrapper= new LambdaQueryWrapper();
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq(WareSkuEntity::getWareId, wareId);
        }
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq(WareSkuEntity::getSkuId, skuId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
               wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateStock(Long skuId, Long wareId, Integer skuNum) {
        LambdaQueryWrapper<WareSkuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WareSkuEntity::getSkuId, skuId).eq(WareSkuEntity::getWareId, wareId);
        WareSkuEntity wareSkuEntity = this.getOne(wrapper);
        if (wareSkuEntity == null) {
            WareSkuEntity wareSku = new WareSkuEntity();
            wareSku.setStock(skuNum);
            wareSku.setWareId(wareId);
            wareSku.setSkuId(skuId);
            wareSku.setStockLocked(0);
            try {
                Map<String, Object> r = productFeignService.info(skuId);
                Map<String, Object> spuInfo = (Map<String, Object>) r.get("skuInfo");
                wareSku.setSkuName((String) spuInfo.get("skuName"));
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            this.save(wareSku);
        } else {
            wareSkuEntity.setStock(wareSkuEntity.getStock() + skuNum);
            this.updateById(wareSkuEntity);
        }
    }


}
